from flask_restful import Resource, reqparse
from flask_shop import models
from flask_shop.order import order_api


class Orders(Resource):

    def get(self):
        """
        获取订单列表
        :return:
        """
        parser = reqparse.RequestParser()
        parser.add_argument('name', type=str, location='args')
        args = parser.parse_args()
        name = args.get('name')
        if name:
            orders = models.Order.query.filter_by(models.Order.name.like(f"%{name}%")).all()
        else:
            orders = models.Order.query.all()
        # 序列化
        return {
            'status': 200,
            'msg': '获取列表成功',
            'data': [order.to_dict() for order in orders]
        }


order_api.add_resource(Orders, '/orders/')


class Order(Resource):
    def get(self, id):
        order = models.Order.query.get(id)
        return {
            'status': 200,
            'msg': '获取成功',
            'data': order.to_dict()
        }


order_api.add_resource(Order, '/order/<int:id>/')


class Expresses(Resource):
    def get(self, id):
        """
        获取快递列表
        :return:
        """
        express_list = models.Express.query.filter(models.Express.oid == id).order_by(models.Express.update_time.asc()).all()
        # 序列化
        return {
            'status': 200,
            'msg': '获取快递成功',
            'data': [express.to_dict() for express in express_list]
        }


order_api.add_resource(Expresses, '/expresses/<int:id>/')
